package flychess.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class XMLParser {
    private static Element rootElement;
    static {
        SAXReader saxReader = new SAXReader();
        InputStream is = XMLParser.class.getResourceAsStream("/config.xml");
        Document document;
        try {
            document = saxReader.read(is);
            // 获取根元素
            rootElement = document.getRootElement();
        } catch (DocumentException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void readHeroList(List<List<String>> list){
        // 获取所有的heroes子元素
        List<Element> heroList = rootElement.element("heroList").elements("heroes");
        for (Element element: heroList) {
            List<String> tmpHeroes = new ArrayList<>();
            for (Element e: element.elements("hero")) {
                tmpHeroes.add(e.element("name").getTextTrim());
            }
            list.add(tmpHeroes);
        }
    }

    public static int getPosNum(String tagName) {
        return Integer.parseInt(rootElement.element("mapConfig").element(tagName).getTextTrim());
    }

    public static int getMapViewConfig(String tagName) {
        return Integer.parseInt(rootElement.element("mapViewConfig").element(tagName).getTextTrim());
    }

    /**
     * 读取xml配置文件中的玩家ID列表
     * @param playerIDs 要读入的ID列表
     */
    public static void readPlayerIDs(List<String> playerIDs) {
        for (Element element: rootElement.element("playerIDs").elements("playerID")) {
            playerIDs.add(element.getTextTrim());
        }
    }

    /**
     * 读取关卡的图标
     * @param icons 存储关卡图标的哈希表
     */
    public static void readIconList(Map<String, String> icons,
                                    Map<Integer, String> indexToIconName,
                                    Map<String, Integer> iconNameToIndex) {
        List<Element> iconList = rootElement.element("iconList").elements();
        for (Element e: iconList) {
            icons.put(e.attributeValue("name"), e.getTextTrim());
            indexToIconName.put(Integer.parseInt(e.attributeValue("id")), e.attributeValue("name"));
            iconNameToIndex.put(e.attributeValue("name"), Integer.parseInt(e.attributeValue("id")));
        }
    }
}